package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        // 查询当前用户搜索的关键词
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria
                        .where("keyword")
                        .is(keyword)
                        .and("userId")
                        .is(userId)),
                ApUserSearch.class
        );

        if (apUserSearch != null) {
            // 该关键词已经存在,更新关键词的时间
            apUserSearch.setCreatedTime(new Date());
            // 更新
            mongoTemplate.save(apUserSearch);
            return;
        }

        // 如果不存在,查询所有的关键词,判断关键词是否超过10个
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query
                        .query(Criteria.where("userId")
                                .is(userId))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime")),
                ApUserSearch.class);

        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setKeyword(keyword);
        apUserSearch.setUserId(userId);

        if (userSearchList != null && userSearchList.size() < 10) {
            // 直接保存
            mongoTemplate.save(apUserSearch);
        } else {
            // 将创建时间最长的搜索词替换掉
            ApUserSearch last = userSearchList.get(userSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(last.getId())), apUserSearch);
        }
    }

    /**
     * 加载用户搜索记录
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        // 获取当前登录用户
        ApUser user = ApUserThreadLocalUtil.getUser();
        List<ApUserSearch> apUserSearchList = null;
        if (user != null && user.getId() != null) {
            apUserSearchList = mongoTemplate.find(Query
                            .query(Criteria.where("userId").is(user.getId()))
                            .with(Sort.by(Sort.Direction.DESC, "createdTime")),
                    ApUserSearch.class);

            return ResponseResult.okResult(apUserSearchList);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 判断是否登录
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 删除
        mongoTemplate.remove(Query.query(Criteria
                .where("id").is(dto.getId())
                .and("userId").is(user.getId())),
                ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
